package com.wrupple.muba.catalogs.client.module.services.logic.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.wrupple.muba.catalogs.client.activity.process.CatalogImportActivityProcess.ImportData;
import com.wrupple.muba.catalogs.client.module.services.logic.CSVParser;
import com.wrupple.muba.catalogs.client.module.services.presentation.impl.JavaScriptAdapter.StringJSOadapter;
import com.wrupple.muba.common.client.JSOHelper;

public class CSVParserImpl implements CSVParser {


	@Override
	public List<JavaScriptObject> parseJSOfromCSV(String[] lines,String[] fields) {
		JsArray<JavaScriptObject> array = csv2json(lines, fields);
		List<JavaScriptObject> regreso = new ArrayList<JavaScriptObject>(array.length());
		JSOHelper.copyIntoList(array, regreso);
		return regreso;
	}



	private JsArray<JavaScriptObject> csv2json(String[] lines,String[] fields) {
		
		JsArray<JavaScriptObject> array = JavaScriptObject.createArray().cast();
		String[] line;
		
		JSONObject temp ;
		for(int i =1; i<lines.length;i++){
			 line = lines[i].split(",");
			 temp = new JSONObject();
			 for(int j = 0; j<line.length;j++){
				 if(line[j]!=null && !line[j].isEmpty()){
					 temp.put(fields[j], getValueOf(line[j]));
				 }
			 }
			 array.set(i-1, temp.getJavaScriptObject());
		}
		
		return array;
	}



	@Override
	public String[] parseCSVLines(String csv) {
		return  csv.split("\n");
	}

	private JSONValue getValueOf(String string) {
		string = string.trim();
		if(string.contains("\"")){
			//quoted string value
			string = string.substring(1, string.length()-1);
		}
		return StringJSOadapter.performJSONValueTransformation(string);
	}



	@Override
	public ImportData parse(String csv) {
		String[] lines = parseCSVLines(csv);
		String[] fields = lines[0].split(",");
		JSONValue jsonValue;
		for (int i = 0; i < fields.length; i++) {
			jsonValue=getValueOf(fields[i]);
			if(jsonValue.isString()==null){
				fields[i]=jsonValue.toString();
			}else{
				fields[i] = jsonValue.isString().stringValue();
			}
			
		}
		List<JavaScriptObject> parsed = parseJSOfromCSV(lines, fields);
		ImportData result = new ImportData(null, fields, parsed);
		return result;
	}

}
